package me.ingxin.android.permission2.task

import android.content.Context
import android.os.Handler
import android.os.Looper
import me.ingxin.android.permission2.permissionGranted
import me.ingxin.android.permission2.request.Request
import me.ingxin.android.permission2.request.RequestNormalFragment
import me.ingxin.android.permission2.request.Task
import me.ingxin.android.permission2.request.TaskChain
import me.ingxin.android.permission2.view.Guide
import me.ingxin.android.permission2.view.GuideView

/**
 * Created on 2023/7/2 by yin
 * 请求常规权限
 */
internal class NormalPermissionsTask : Task {

    private val mainHandler = Handler(Looper.getMainLooper())
    private var whileView: GuideView? = null
    private var settingsView: GuideView? = null

    override fun runTask(chain: TaskChain, request: Request) {
        //被前面的任务设置了调过普通权限申请
        if (request.skipRequestNormaPermission) {
            chain.proceed(request)
            return
        }

        whileView?.applyDismiss()
        settingsView?.applyDismiss()

        val requestList = ArrayList<String>()
        val grantedPermissions = ArrayList<String>()
        for (permission in request.normalPermissions) {
            if (chain.context.permissionGranted(permission)) {
                grantedPermissions.add(permission)
            } else {
                requestList.add(permission)
            }
        }

        if (requestList.isEmpty()) {
            chain.proceed(request)
            return
        }

        if (request.tipsWhileRequest) {
            //当用户选择了不再询问时，可能不会弹出系统框被直接拒绝，等待一小段时间，过滤这种情况
            mainHandler.postDelayed({
                showReasonViewWhileRequest(
                    chain.context, requestList, request.guide
                )
            }, 350)
        }

        val fragment = RequestNormalFragment()
        fragment.requestNormalPermissions(requestList) { _, _, notShownList ->
            mainHandler.removeCallbacksAndMessages(null)
            whileView?.applyDismiss()
            if (request.settings && notShownList.isNotEmpty()) {
                toSettings(chain, request, notShownList)
            } else {
                chain.proceed(request)
            }
        }
        chain.fragmentManager.beginTransaction().add(fragment, fragment.javaClass.name)
            .commitAllowingStateLoss()
    }

    private fun showReasonViewWhileRequest(
        context: Context, permissions: List<String>, explanation: Guide
    ) {
        whileView = explanation.getTipsView(context, permissions)
        whileView?.applyShow()
    }

    private fun toSettings(chain: TaskChain, request: Request, notShownList: List<String>) {
        settingsView = request.guide.getToSettingsView(chain.context, notShownList, {
            //用户选择去设置中心
            it.applyDismiss()
            val fragment = RequestNormalFragment()
            fragment.requestToSettings { runSelfAgain(chain, request) }
            chain.fragmentManager.beginTransaction().add(fragment, fragment.javaClass.name)
                .commitAllowingStateLoss()
        }) {
            //用户拒绝去设置中心
            it.applyDismiss()
            chain.proceed(request)
        }
        settingsView?.applyShow()
    }

    /**
     * 再一次执行自己
     */
    private fun runSelfAgain(chain: TaskChain, request: Request) {
        runTask(chain, request)
    }

}